/**
 * 封装微信的的request
 */
import api from './index'
const WxApiRoot = 'https://api.zhengpai1688.com';
function request(url, data = {}, msg, method, header,type) {
	// 如果既有query和body那么就是application/json header提交
	if (header==true) {
		header ={'content-type': 'application/x-www-form-urlencoded'}
	} else {
		// body 用此方法提交            
		header = {
			 'Content-Type': 'application/json;charset=UTF-8'
		}
	}
  if (!!msg) {
    uni.showLoading({
      title: msg, // 数据请求前loading
      mask:true
    })
  }
  return new Promise(function(resolve, reject) {
    uni.request({
      url: WxApiRoot + url,
      data: data,
      method: method,
      responseType: type || 'text',
      header: Object.assign(header, {
        'X-Litemall-Token': uni.getStorageSync('token')
      }),
      success: function(res) {
        if (!!msg) {
			setTimeout(()=>{
				uni.hideLoading()
			},1000)
            
        }
		
		console.log('获取')
		// 重新登录
		if (res.data.errno==501) {
			uni.login({
			  provider: 'weixin',
			  success: function (res) {
				  console.log(res.code)
				  api.common.login({code:res.code,userInfo:{}}).then(ret=>{
					  console.log(ret)
					  console.log('登录成功')
					  uni.setStorageSync('token',ret.data.token)
					  uni.setStorageSync('userinfo',ret.data)
					  var pages = getCurrentPages();
					  var currPage = pages[pages.length - 1]; //当前页面
					  console.log(currPage.options)
					  console.log(currPage.route)
					currPage.onLoad(currPage.options)
				  })
			
			  },
			  fail(){
				  console.log('失败')
			  }
			});
		}
        // 登陆失效，重新登陆
     if (res.data.errno!=0) {
          let errorMessage = res.data.errmsg;
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration:3000
          })
        }
        resolve(res.data)
      },
      fail: function(err) {
        if (!!msg) {
          uni.hideLoading()
        }
        let errorMessage = err.errmsg;
        uni.showToast({
          title: errorMessage,
          icon: 'none'
        })
        reject(err)
      }
    })
  });
}

function get(url, params, msg, header = {},type) {
  return request(url, params, msg, 'GET', header,type)
}

function post(url, data, msg, header = {}) {
  return request(url, data, msg, 'POST', header)
}
function deletes(url, data, msg, header = {}) {
  return request(url, data, msg, 'DELETE', header)
}
export default {
  get,
  post,deletes,
  requestUrl:WxApiRoot
}
